# serenity_tags.py
# Author: Nico Marrero
# Copyright 2012 Nico Marrero
#
#	 This file is part of django-serenity.
#
#    django-serenity is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    django-serenity is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with django-serenity.  If not, see <http://www.gnu.org/licenses/>.

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe

import re

register = template.Library()

@register.filter
def getitem ( item, string ):
    try:
        if hasattr(item,string):
            return getattr(item,string)
        return item[string]
    except KeyError:
        return item.get(string,'')

#From http://stackoverflow.com/questions/721035/django-templates-stripping-spaces
@stringfilter
def spacify(value, autoescape=None):
    if autoescape:
        esc = conditional_escape
    else:
        esc = lambda x: x
    return mark_safe(re.sub('\s', '&'+'nbsp;', esc(value)))
spacify.needs_autoescape = True
register.filter(spacify)